package com.tenton.servlet;

import com.tenton.pojo.ShoppingCart;
import com.tenton.service.CartService;
import com.tenton.service.Impl.CartServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * @Date: 2021/1/20
 * @Author: Tenton
 * @Description:
 */
@WebServlet(name = "UpdateCartServlet",urlPatterns = "/updateCartServlet")
public class UpdateCartServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式，防止乱码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        CartService cartService = new CartServiceImpl();
        //获取session中的用户Id
        HttpSession session = request.getSession();
        //当前用户Id
        int userId = (int) session.getAttribute("userId");
        //购物车Id
        int id = Integer.parseInt(request.getParameter("id"));
        ShoppingCart cart = cartService.getCartById(id);
        //购买数量
        int num = Integer.parseInt(request.getParameter("num"));
        if (cart.getUserId().equals(userId) && num != cart.getNum()){
            BigDecimal bd = new BigDecimal(num);
            BigDecimal totalPrice = cart.getPrice().multiply(bd);
            cart.setNum(num);
            cart.setTotalPrice(totalPrice);
            cartService.updateCart(cart);
        }
        request.getRequestDispatcher("/listCartServlet").forward(request,response);
    }
}
